import 'package:flutter/material.dart';
import 'package:ribo_base_core/base_models/base_chart_axis.dart';
import 'package:ribo_base_core/base_models/base_chart_dumbbells_model.dart';
import 'package:ribo_base_core/base_models/base_chart_model.dart';
import 'package:ribo_base_core/base_styles/base_chart_style.dart';
import 'base_chart.dart';

class BaseChartDumbbells extends StatefulWidget {
  BaseChartDumbbells({Key key, @required this.model}) : super(key: key);
  final BaseChartDumbbellsModel model;

  @override
  _BaseChartDumbbellsState createState() => _BaseChartDumbbellsState();
}

class _BaseChartDumbbellsState extends State<BaseChartDumbbells> {
  Map<String, dynamic> _option;

  @override
  Widget build(BuildContext context) {
    _handleModel();

    return BaseChart(
      model: BaseChartModel(style: widget.model?.style, option: this._option),
    );
  }

  void _handleModel() {
    List<BaseChartDumbbellsData> dumbbellsData = widget.model?.dumbbellsData;
    BaseChartAxis baseChartAxis = BaseChartAxis();
    List<String> colors = widget.model?.colors ?? ['grey'];
    String lineColor = widget.model?.lineColor;
    var colorLength = colors.length;

    List<String> xAxisData = [];
    dumbbellsData.forEach((element) {
      List list = element.datas;
      xAxisData.add(list[0].name.substring(list[0].name.lastIndexOf('-')+1));
    });

    this._option = {
      "xAxis": {
        ...(widget.model?.axis ?? baseChartAxis).toJson()['xAxis'],
        "type": 'category',
        "data": xAxisData
      },
      'legend': {
        ...BaseChartLegendStyle().toJson(),
        ...widget.model?.style?.legend?.toJson() ?? {},
      },
      "yAxis": {
        ...(widget.model?.axis ?? baseChartAxis).toJson()['yAxis'],
        "type": 'value',
      },
      "dataZoom": widget.model.dataZoom,
      "series": dumbbellsData
          .asMap()
          .keys
          .map((i) =>
      {
        "data": dumbbellsData[i]
            .datas
            .asMap()
            .keys
            .map((e) =>
        {
          "value": [
            i,
            dumbbellsData[i].datas[e].value,
          ],
          "itemStyle": {
            "color": colors[e % colorLength]
          },
          "label": {"show": true, "position": 'left', "fontSize": 8}
        })
            .toList(),
        "type": 'line',
        "symbol": 'circle',
        "symbolSize": 6,
        "itemStyle": {"color": colors[i % colorLength]},
        "lineStyle": {"color": lineColor, "width": 3}
      })
          .toList()
    };
  }
}
